<template>
  <el-card class="history-card">
    <template #header>
      <div class="history-header">
        <div class="header-left">
          <div class="header-icon">📊</div>
          <div class="header-content">
            <h3>计算历史</h3>
            <p>历史计算记录和趋势分析</p>
          </div>
        </div>
      </div>
    </template>

    <!-- 奖励趋势图表 -->
    <div class="trend-section">
      <div class="trend-header">
        <h4>奖励趋势分析</h4>
        <p>历史奖励金额变化趋势</p>
      </div>
      <div class="trend-chart">
        <div v-if="!history.length" class="empty-state">
          <div class="empty-icon">📊</div>
          <h4 class="empty-title">暂无历史数据</h4>
          <p class="empty-description">开始计算奖励后，这里将显示趋势分析图表</p>
        </div>
        <echart
            v-else
            :option="trendChartOption"
            :style="{ height: isMobile ? '250px' : '350px' }"
            autoresize
        />
      </div>
    </div>

    <!-- 历史记录表格 -->
    <div class="table-section">
      <div class="table-header">
        <div class="table-left">
          <h4>历史记录</h4>
          <p>点击记录可重新加载数据</p>
        </div>
        <div class="table-actions">
          <el-button
              type="danger"
              plain
              :icon="Delete"
              @click="confirmBatchDelete"
              class="action-btn delete-btn"
              v-if="selectedRecords.length"
          >
            <span class="btn-text">删除选中</span>
          </el-button>
          <el-button
              type="info"
              plain
              :icon="Download"
              @click="exportHistory"
              class="action-btn export-btn"
          >
            <span class="btn-text">导出历史</span>
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <div v-if="!history.length" class="empty-state">
          <div class="empty-icon">📋</div>
          <h4 class="empty-title">暂无历史记录</h4>
          <p class="empty-description">完成第一次计算后，历史记录将显示在这里</p>
        </div>
        <el-table
            v-else
            :data="history"
            stripe
            style="width: 100%"
            @row-click="loadHistory"
            @selection-change="handleSelectionChange"
            :max-height="isMobile ? '300' : '400'"
            class="history-table"
        >
          <el-table-column type="selection" width="55"></el-table-column>

          <el-table-column prop="timestamp" label="时间" min-width="30%">
            <template #default="{row}">
              <div class="time-cell">
                <div class="time-icon">🕒</div>
                <div class="time-info">
                  <div class="time-date">{{ formatDate(row.timestamp) }}</div>
                  <div class="time-time">{{ formatTime(row.timestamp) }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="total" label="总分" min-width="20%">
            <template #default="{row}">
              <div class="score-cell">
                <span class="score-value">{{ row.total }}</span>
                <span class="score-label">分</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="currentRank" label="排名" min-width="15%">
            <template #default="{row}">
              <div class="rank-cell">
                <span class="rank-icon">🏆</span>
                <span class="rank-value">{{ row.currentRank }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="totalReward" label="总奖励" min-width="20%">
            <template #default="{row}">
              <div class="reward-cell">
                <span class="reward-currency">¥</span>
                <span class="reward-value">{{ row.totalReward.toFixed(2) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="120">
            <template #default="{row}">
              <div class="action-cell">
                <el-tooltip content="下载报告" placement="top">
                  <el-button
                      text
                      :icon="Download"
                      @click.stop="downloadPdf(row.id)"
                      class="table-action-btn download"
                  />
                </el-tooltip>

                <el-tooltip content="删除记录" placement="top">
                  <el-button
                      text
                      :icon="Delete"
                      @click.stop="confirmDelete(row.id)"
                      class="table-action-btn delete"
                  />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-card>
</template>

<script>
import {use} from 'echarts/core'
import {CanvasRenderer} from 'echarts/renderers'
import {LineChart} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {Delete, Download} from "@element-plus/icons-vue"
import {ElMessage} from 'element-plus'
import * as XLSX from 'xlsx'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent
])

export default {
  name: 'HistoryManager',
  components: {
    echart: VChart,
  },
  props: {
    history: {
      type: Array,
      default: () => []
    },
    isMobile: {
      type: Boolean,
      default: false
    },
    subjects: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedRecords: []
    }
  },
  computed: {
    Delete() {
      return Delete
    },
    Download() {
      return Download
    },
    sortedHistory() {
      return [...this.history].reverse()
    },
    trendChartOption() {
      if (!this.sortedHistory.length) return null
      return {
        title: {
          text: '奖励趋势',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 16,
            fontWeight: 600,
            color: '#303133'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: this.formatTooltip,
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e4e7ed',
          borderWidth: 1,
          textStyle: {
            color: '#303133'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.sortedHistory.map(h => new Date(h.timestamp).toLocaleString()),
          axisLabel: {
            rotate: 45,
            interval: this.calculateInterval(), // 使用动态计算的间隔
            formatter: this.formatDate,
            color: '#606266',
            fontSize: 10,
            showMaxLabel: true, // 始终显示最后一个标签
            showMinLabel: true  // 始终显示第一个标签
          },
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '奖励金额 (元)',
          axisLabel: {
            formatter: '¥{value}',
            color: '#606266'
          },
          axisLine: {
            lineStyle: {
              color: '#e4e7ed'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [{
          name: '奖励金额',
          type: 'line',
          data: this.sortedHistory.map(h => h.totalReward),
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF',
            borderColor: '#fff',
            borderWidth: 2
          },
          lineStyle: {
            color: '#409EFF',
            width: 3
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(64,158,255,0.3)'
              }, {
                offset: 1, color: 'rgba(64,158,255,0.1)'
              }]
            }
          }
        }]
      }
    }
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedRecords = selection
    },

    // 计算x轴标签间隔
    calculateInterval() {
      const dataLength = this.sortedHistory.length
      if (dataLength <= 10) return 0 // 数据少时显示所有标签
      if (dataLength <= 20) return 1 // 每2个显示1个
      if (dataLength <= 50) return 2 // 每3个显示1个
      if (dataLength <= 100) return 4 // 每5个显示1个
      return Math.floor(dataLength / 20) // 最多显示20个标签
    },

    // 格式化日期显示
    formatDate(value) {
      const date = new Date(value);
      const now = new Date();

      const diffMs = now - date; // 毫秒差
      const diffSeconds = Math.floor(diffMs / 1000);
      const diffMinutes = Math.floor(diffSeconds / 60);
      const diffHours = Math.floor(diffMinutes / 60);

      // 把时间部分清零，只比较日期（年月日）
      const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      const diffDays = Math.floor((startOfToday - startOfDate) / (1000 * 60 * 60 * 24));

      if (diffDays === 0) {
        // 今天，根据小时、分钟判断更精确的时间描述
        if (diffHours > 0) {
          return `${diffHours}小时前`;
        } else if (diffMinutes > 0) {
          return `${diffMinutes}分钟前`;
        } else {
          return '刚刚';
        }
      } else if (diffDays === 1) {
        return '昨天';
      } else if (diffDays <= 7) {
        return `${diffDays}天前`;
      } else if (diffDays <= 30) {
        const weeks = Math.floor(diffDays / 7);
        return `${weeks}周前`;
      } else {
        // 超过30天显示具体日期，格式 yyyy-MM-dd
        return date.toLocaleDateString();
      }
    },
    loadHistory(row) {
      this.$emit('load-history', row)
    },
    confirmDelete(id) {
      this.$emit('delete-record', id)
    },
    confirmBatchDelete() {
      if (!this.selectedRecords.length) {
        ElMessage.warning('请先选择要删除的记录')
        return
      }
      this.$emit('batch-delete', this.selectedRecords)
    },
    downloadPdf(id) {
      this.$emit('download-pdf', id)
    },
    exportHistory() {
      const data = this.history.map(h => ({
        '时间': new Date(h.timestamp).toLocaleString(),
        '总分': h.total,
        '当前排名': h.currentRank,
        '总奖励': h.totalReward,
        '基础奖励': h.base,
        '额外奖励': h.extra,
        '特殊奖励': h.special,
        '基础奖励说明': h.baseDesc,
        '额外奖励说明': h.extraDesc,
        '特殊奖励说明': h.specialDesc
      }))

      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(data, {
        header: Object.keys(data[0])
      })

      ws['!cols'] = [
        {wch: 20}, {wch: 10}, {wch: 10},
        {wch: 15}, {wch: 15}, {wch: 15},
        {wch: 15}, {wch: 30}, {wch: 30},
        {wch: 30}
      ]

      XLSX.utils.book_append_sheet(wb, ws, '奖励计算历史')
      XLSX.writeFile(wb, `奖励计算历史_${new Date().toLocaleDateString()}.xlsx`)

      ElMessage.success('历史记录导出成功')
    },
    formatTooltip(params) {
      const data = params[0]
      return `${data.name}<br/>奖励金额：¥${data.value.toFixed(2)}`
    },
    formatTime(value) {
      const date = new Date(value)
      return `${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
/* 基础变量定义 */
:root {
  --text-primary: #303133;
  --text-regular: #606266;
  --text-light: #909399;
  --border-color: #e4e7ed;
  --shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  --shadow-medium: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
  --shadow-heavy: 0 8px 30px 0 rgba(0, 0, 0, 0.15);
  --border-radius: 8px;
  --border-radius-small: 6px;
  --spacing-base: 8px;
  --spacing-sm: 12px;
  --spacing-md: 20px;
  --spacing-lg: 24px;
  --spacing-xl: 32px;
  --transition-base: all 0.3s;
  --transition-fast: all 0.2s;
  --font-size-base: 14px;
  --font-size-sm: 12px;
  --font-size-lg: 16px;
  --font-size-xl: 20px;
  --font-size-2xl: 24px;
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --danger-color: #F56C6C;
}

/* 卡片样式 */
.history-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: var(--border-radius);
  box-shadow: var(--shadow-medium);
  transition: var(--transition-base);
}

.history-card:hover {
  box-shadow: var(--shadow-heavy);
  transform: translateY(-2px);
}

/* 头部样式 */
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-lg);
}

.header-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.header-icon {
  font-size: var(--font-size-2xl);
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--gradient-primary);
  color: white;
  border-radius: var(--border-radius-small);
  box-shadow: var(--shadow-light);
}

.header-content h3 {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
}

.header-content p {
  margin: 0;
  color: var(--text-light);
  font-size: var(--font-size-base);
}

.table-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.action-btn {
  border-radius: var(--border-radius-small);
  font-weight: 500;
  transition: var(--transition-base);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-medium);
}

.delete-btn:hover {
  background: var(--danger-color);
  color: white;
}

.export-btn:hover {
  background: var(--primary-color);
  color: white;
}

/* 趋势图表区域 */
.trend-section {
  background: rgba(255, 255, 255, 0.6);
  border-radius: var(--border-radius-small);
  padding: var(--spacing-lg);
  border: 1px solid rgba(255, 255, 255, 0.4);
  margin-bottom: var(--spacing-lg);
}

.trend-header {
  margin-bottom: var(--spacing-lg);
  text-align: center;
}

.trend-header h4 {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.trend-header p {
  margin: 0;
  color: var(--text-light);
  font-size: var(--font-size-base);
}

.trend-chart {
  background: white;
  border-radius: var(--border-radius-small);
  padding: var(--spacing-md);
  box-shadow: var(--shadow-light);
}

/* 表格区域 */
.table-section {
  background: rgba(255, 255, 255, 0.6);
  border-radius: var(--border-radius-small);
  padding: var(--spacing-lg);
  border: 1px solid rgba(255, 255, 255, 0.4);
}

.table-header {
  margin-bottom: var(--spacing-lg);
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: var(--spacing-lg);
}

.table-header h4 {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.table-header p {
  margin: 0;
  color: var(--text-light);
  font-size: var(--font-size-base);
}

.table-left {
  display: flex;
  align-items: center;
  /* gap: var(--spacing-md); */
  flex-direction: column;
}

.table-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.table-container {
  background: white;
  border-radius: var(--border-radius-small);
  overflow: hidden;
  box-shadow: var(--shadow-light);
}

.history-table {
  margin: 0;
}

/* 表格单元格样式 */
.time-cell {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.time-icon {
  font-size: var(--font-size-lg);
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 50%;
}

.time-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-date {
  font-size: var(--font-size-base);
  font-weight: 500;
  color: var(--text-primary);
}

.time-time {
  font-size: var(--font-size-sm);
  color: var(--text-light);
}

.score-cell {
  display: flex;
  align-items: baseline;
  gap: var(--spacing-xs);
}

.score-value {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.score-label {
  font-size: var(--font-size-sm);
  color: var(--text-light);
}

.rank-cell {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.rank-icon {
  font-size: var(--font-size-base);
}

.rank-value {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.reward-cell {
  display: flex;
  align-items: baseline;
  gap: var(--spacing-xs);
}

.reward-currency {
  font-size: var(--font-size-base);
  color: var(--success-color);
  font-weight: 500;
}

.reward-value {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--success-color);
}

.action-cell {
  display: flex;
  gap: var(--spacing-xs);
}

.table-action-btn {
  font-size: var(--font-size-lg);
  color: var(--text-light);
  transition: var(--transition-fast);
  padding: 6px;
  border-radius: var(--border-radius-small);
}

.table-action-btn:hover {
  transform: scale(1.2);
}

.table-action-btn.download:hover {
  color: var(--primary-color);
  background: rgba(64, 158, 255, 0.1);
}

.table-action-btn.delete:hover {
  color: var(--danger-color);
  background: rgba(245, 108, 108, 0.1);
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: var(--spacing-xl);
  color: var(--text-light);
  background: rgba(255, 255, 255, 0.8);
  border-radius: var(--border-radius-small);
  box-shadow: var(--shadow-light);
  margin-top: var(--spacing-lg);
}

.empty-icon {
  font-size: var(--font-size-2xl);
  margin-bottom: var(--spacing-sm);
}

.empty-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.empty-description {
  font-size: var(--font-size-base);
  margin-bottom: var(--spacing-md);
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .history-header {
    gap: var(--spacing-md);
  }

  .table-actions {
    gap: var(--spacing-sm);
  }

  .trend-section,
  .table-section {
    padding: var(--spacing-lg);
  }
}

@media screen and (max-width: 768px) {
  .history-header {
    flex-direction: column;
    gap: var(--spacing-md);
    text-align: center;
    padding: var(--spacing-md) 0;
  }

  .header-left {
    order: 1;
  }

  .table-actions {
    order: 2;
    justify-content: center;
  }

  .header-icon {
    width: 40px;
    height: 40px;
    font-size: var(--font-size-xl);
  }

  .header-content h3 {
    font-size: var(--font-size-lg);
    margin-bottom: var(--spacing-xs);
  }

  .header-content p {
    font-size: var(--font-size-sm);
  }

  .action-btn {
    flex: 1;
    justify-content: center;
    min-width: 120px;
  }

  .btn-text {
    display: none;
  }

  .trend-section,
  .table-section {
    padding: var(--spacing-md);
  }

  .trend-header h4,
  .table-header h4 {
    font-size: var(--font-size-base);
  }

  .trend-header p,
  .table-header p {
    font-size: var(--font-size-sm);
  }

  .time-cell,
  .rank-cell {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }

  .time-icon,
  .rank-icon {
    width: 32px;
    height: 32px;
    font-size: var(--font-size-lg);
  }

  .time-date,
  .rank-value {
    font-size: var(--font-size-base);
  }

  .time-time {
    font-size: var(--font-size-sm);
  }

  .score-cell {
    text-align: center;
  }

  .score-value {
    font-size: var(--font-size-base);
  }

  .score-label {
    font-size: var(--font-size-sm);
  }

  .reward-cell {
    text-align: center;
  }

  .reward-currency {
    font-size: var(--font-size-sm);
  }

  .reward-value {
    font-size: var(--font-size-base);
  }

  .action-cell {
    justify-content: center;
  }

  .table-action-btn {
    font-size: var(--font-size-base);
    padding: 8px;
  }

  .empty-state {
    padding: var(--spacing-lg);
  }

  .empty-icon {
    font-size: var(--font-size-xl);
  }

  .empty-title {
    font-size: var(--font-size-base);
  }

  .empty-description {
    font-size: var(--font-size-sm);
  }
}

@media screen and (max-width: 480px) {
  .history-header {
    gap: var(--spacing-sm);
    padding: var(--spacing-sm) 0;
  }

  .header-icon {
    width: 36px;
    height: 36px;
    font-size: var(--font-size-lg);
  }

  .header-content h3 {
    font-size: var(--font-size-base);
  }

  .header-content p {
    font-size: var(--font-size-xs);
  }

  .action-btn {
    min-width: 100px;
    height: 40px;
    font-size: var(--font-size-sm);
  }

  .trend-section,
  .table-section {
    padding: var(--spacing-sm);
  }

  .trend-header h4,
  .table-header h4 {
    font-size: var(--font-size-sm);
  }

  .trend-header p,
  .table-header p {
    font-size: var(--font-size-xs);
  }

  .time-icon,
  .rank-icon {
    width: 28px;
    height: 28px;
    font-size: var(--font-size-base);
  }

  .time-date,
  .rank-value {
    font-size: var(--font-size-sm);
  }

  .time-time {
    font-size: var(--font-size-xs);
  }

  .score-value {
    font-size: var(--font-size-sm);
  }

  .score-label {
    font-size: var(--font-size-xs);
  }

  .reward-currency {
    font-size: var(--font-size-xs);
  }

  .reward-value {
    font-size: var(--font-size-sm);
  }

  .table-action-btn {
    font-size: var(--font-size-sm);
    padding: 6px;
  }

  .empty-state {
    padding: var(--spacing-md);
    margin-top: var(--spacing-sm);
  }

  .empty-icon {
    font-size: var(--font-size-lg);
  }

  .empty-title {
    font-size: var(--font-size-sm);
  }

  .empty-description {
    font-size: var(--font-size-xs);
  }
}
</style> 